<?php
declare (strict_types = 1);

namespace command\factory;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;

class CodeFactory extends Command
{

    private $config = [];

    protected function configure()
    {
        // 指令配置
        $this->setName('factory:run')
            ->addArgument('op', Argument::OPTIONAL, "操作")
            ->addOption('c', null, Option::VALUE_REQUIRED, '配置文件')
            ->setDescription('auto create code');     
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            if ($input->hasOption('c')) {
                $configfile = $input->getOption('c');
            }else{
                $configfile = 'FactoryConfig';
            }
            
            $this->parseConfig($this->readConfig($configfile))
                 ->createDataBase()
                 ->createModel()
                 ->createService()
                 ->createController();
            
        } catch (\Throwable $th) {
            var_dump($th->getTrace()[1]['file'],$th->getTrace()[1]['line']);
            return_error(['info'=>$th->getMessage()]);
        }
    }

    /**
     * 读取配置
     *
     * @return void
     */
    private function readConfig($configfile)
    {
        $config = [];
        //获取代码工厂生产配置
        $configFile = app()->getRootPath().DIRECTORY_SEPARATOR.'factory'.DIRECTORY_SEPARATOR.$configfile.'.php';
        if(is_file($configFile)){
            $config = include_once $configFile;
        }

        return $config;
    }

    /**
     * 解析全量配置
     *
     * @param array $config
     * @return object
     */
    private function parseConfig($config)
    {
        if(empty($config)){
            return_error(['info'=>'配置信息为空']);
        }
        $this->config = ConfigParse::parse($config);
        return $this;
    } 

    /**
     * 创建数据库
     *
     * @return object
     */
    protected function createDataBase()
    {
       Database::init($this->config['db'])->create();
       return $this;
    }

    /**
     * 创建模型
     *
     * @return object
     */
    protected function createModel()
    {
        Model::init($this->config['model'])->create();
        return $this;
    }

    /**
     * 创建服务
     *
     * @return object
     */
    protected function createService()
    {
        Service::init($this->config['service'])->create();
        return $this;
    }

    /**
     * 创建控制器
     *
     * @return object
     */
    protected function createController()
    {
        Controller::init($this->config['api'])->create();
        return $this;
    }

    protected function createPlugin()
    {

    }
}
